package ch.elexis.persistence.couchbase

import collection.JavaConversions._
import ch.elexis.core.data.IPersistentObjectManager
import java.net.URI
import com.couchbase.client.CouchbaseClient
import scala.actors.threadpool.TimeUnit
import ch.elexis.core.data.IPersistentObject

object PersistentCouchManager extends IPersistentObjectManager {
    val rootID=":___elexis-d____:"
    val cacheTime=60;
	var client : CouchbaseClient = null
  
	def connect(dbName: String, hosts: String*) = {
	  var uris = List[URI]()
	  hosts.foreach(s => uris=uris :+ URI.create(s)) 
	  client = new CouchbaseClient(uris,dbName,"")
	}
	
	def close = if(client!=null) client.shutdown(1,java.util.concurrent.TimeUnit.MINUTES);
	
	override def getRootObject : IPersistentObject= {
	  val ret =client.getAndTouch(rootID,86400)
	  if(ret!=null && ret.getValue()!=null){
	    return ret.getValue().asInstanceOf[IPersistentObject];
	  }else{
	    val couch=new Couch("DiesIstDieDBUID","DIesIstManantUID");
	    store(couch)
	    return couch;
	  }
	}

	def get(id:String) : PersistentCouchObject = {
	  val ret=client.getAndTouch(id,cacheTime);
	  if(ret==null){
	    return null;
	  }else{
	    val pco=ret.getValue().asInstanceOf[PersistentCouchObject];
	    pco.set(PersistentCouchObject.FLD_ID,id)
	    pco.setCAS(ret.getCas());
	    pco
	  }
	}
	def store(pco: PersistentCouchObject) = {
	  client.cas(pco.getId(),pco.getCas,pco)
	  //client.asyncCAS(pco.getId(),pco.getCas,pco)
	}
		 
}